# -*- coding: utf8 -*-
'''
Created on 2009/10/26

@author: matianyi
'''

import os
import sys
import logging
from datetime import datetime,timedelta
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from org.andolphin import *
from org.andolphin.models import *
from django import forms

class LoginForm(forms.Form):
    username = forms.CharField(required = True)
    password = forms.CharField(required = False)

class LoginPage(webapp.RequestHandler):
    def post(self):
        r = None
        form = LoginForm(self.request.POST)
        if form.is_valid():
            user_id = form.cleaned_data['username']
            pwd=password_md5(form.cleaned_data['password'])
            user = User.gql("WHERE user_id = :1", user_id).get()
            if not user:
                r = Result(RESULT_USER_NOT_EXISTS, RESULT_USER_NOT_EXISTS_MSG,{})
            elif user.password!= pwd:
                r = Result(RESULT_PASSWORD_ERROR, RESULT_PASSWORD_ERROR_MSG,{})
            else:
                expire = datetime.datetime.now() + timedelta(days=1)
                token = encode_token(user.password, expire)
                user.auth_expire = expire
                user.auth_token = token
                user.put()
                r = Result(RESULT_SUCCESS, RESULT_SUCCESS_MSG,
                           {'username':user_id, 
                            'password':form.cleaned_data['password'] ,
                            'email':user.email,
                            'expire':expire.strftime('%Y%m%d%H%M%S'),
                            'token':token})
        else:
            r = Result(RESULT_INPUT_ERROR, RESULT_INPUT_ERROR_MSG,
                        {'error_message': cleaned_errors(form.errors)})
            
        render_json(self.response, r)
        
    def get(self):
        r = Result(RESULT_METHOD_NOT_ALLOWED, RESULT_METHOD_NOT_ALLOWED_MSG,{})
        render_json(self.response, r)


class RegisterForm(forms.Form):
    username = forms.CharField(min_length=4, max_length=20)
    password = forms.CharField(min_length=4, max_length=8)
    email = forms.EmailField()

class RegisterPage(webapp.RequestHandler):
    def post(self):
        r = None
        form = RegisterForm(self.request.POST)
        if form.is_valid():
            if User.gql("WHERE user_id = :1", form.cleaned_data['username']).get():
                r = Result(RESULT_USER_DUPLICATE, RESULT_USER_DUPLICATE_MSG,{})
            else:
                pwd=password_md5(form.cleaned_data['password'])
                expire = datetime.datetime.now() + timedelta(days=1)
                token = encode_token(pwd, expire)
                u = User(user_id = form.cleaned_data['username'],
                         password = pwd,
                         email = form.cleaned_data['email'],
                         auth_expire = expire,
                         token = token,
                         sync_version = 1)
                u.put()
                r = Result(RESULT_SUCCESS, RESULT_SUCCESS_MSG,
                           {'username':u.user_id, 
                            'password':form.cleaned_data['password'],
                            'email':u.email,
                            'sync_version':u.sync_version,
                            'expire':expire.strftime('%Y%m%d%H%M%S'),
                            'token':token})
        else:
            r = Result(RESULT_INPUT_ERROR, RESULT_INPUT_ERROR_MSG,
                 {'error_message': cleaned_errors(form.errors)})
        
        render_json(self.response, r)
        
    def get(self):
        r = Result(RESULT_METHOD_NOT_ALLOWED, RESULT_METHOD_NOT_ALLOWED_MSG,{})
        render_json(self.response, r)

class SyncVersionPage(webapp.RequestHandler):
    def get(self):
        username = self.request.headers['username'];
        user = User.gql('WHERE user_id = :1',[username]).get()
        r = None
        if user:
            r = Result(RESULT_SUCCESS, RESULT_SUCCESS_MSG,{
                            'username':username,
                            'sync_version':user.sync_version
                            })
        else:
            r = Result(RESULT_INPUT_ERROR, RESULT_INPUT_ERROR_MSG,{'username':username})
        render_json(self.response, r)
        
    def post(self):
        r = Result(RESULT_METHOD_NOT_ALLOWED, RESULT_METHOD_NOT_ALLOWED_MSG,{})
        render_json(self.response, r)
